<template>
  <LoginHeader>联合登录</LoginHeader>
  <section class="container">
    <nav class="tab">
      <a href="javascript:;" @click="hasAccount = true" :class="{active:hasAccount}">
        <i class="iconfont icon-bind" />
        <span>已有小兔鲜账号，请绑定手机</span>
      </a>
      <a href="javascript:;" @click="hasAccount = false" :class="{active:!hasAccount}">
        <i class="iconfont icon-edit" />
        <span>没有小兔鲜账号，请完善资料</span>
      </a>
    </nav>
    <!-- 有账号 =》需要绑定qq号 -->
    <div class="tab-content" v-if="hasAccount">
      <CallbackBind :unionId="unionId"/>
    </div>
    <!-- 没有账号=》 注册小兔鲜并绑定qq号-->
    <div class="tab-content" v-else>
      <CallbackPatch :unionId="unionId"/>
    </div>
  </section>
  <LoginFooter />
</template>

<script>

import LoginHeader from './components/login-header'
import LoginFooter from './components/login-footer'
import CallbackBind from './components/callback-bind'
import CallbackPatch from './components/callback-patch'
import { ref } from 'vue'
import { userQQLogin } from '@/api/user'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { message } from '@/components/Message/index.js'
export default {
  name: 'PageCallback',
  components: { LoginHeader, LoginFooter, CallbackBind, CallbackPatch },
  setup () {
    // 是否有账号
    const hasAccount = ref(false)
    const router = useRouter()
    const store = useStore()
    // qq身份标识
    const unionId = ref('')

    /**
     * 已有小兔子账号同时绑定了QQ（最终目的）
     * 步骤：
      1.  检查QQ是否授权登录
      2.  如果授权登录获取openId
      3.  使用openId获取后台用户数据存vuex
      4.  跳转首页
     */
    if (window.QC.Login.check) {
      window.QC.Login.getMe(async (openId) => {
        // console.log('QQ用户身份标识：', openId)
        unionId.value = openId

        try {
          const { result } = await userQQLogin(openId)
          // 存储登录人的信息
          store.commit('user/setToken', result)
          // 登录成功之后 =》 合并之前本地购物车数据，到登录人名下
          await store.dispatch('cart/mergeCartAction')
          message({ type: 'success', text: 'QQ登录成功！' })
          router.replace('/')
        } catch (error) {
          message({ type: 'error', text: 'QQ登录失败！' })
        }
      })
    }
    return {
      hasAccount,
      unionId
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  padding: 25px 0;
}
.tab {
  background: #fff;
  height: 80px;
  padding-top: 40px;
  font-size: 18px;
  text-align: center;
  a {
    color: #666;
    display: inline-block;
    width: 350px;
    line-height: 40px;
    border-bottom: 2px solid #e4e4e4;
    i {
      font-size: 22px;
      vertical-align: middle;
    }
    span {
      vertical-align: middle;
      margin-left: 4px;
    }
    &.active {
      color: @xtxColor;
      border-color: @xtxColor;
    }
  }
}
.tab-content {
  min-height: 600px;
  background: #fff;
}
</style>
